<?php
	$username = "root";
	$password = "papamama";
	$hostname = "localhost";
	
	$dbhandle = mysql_connect($hostname, $username, $password) or die ("Unable to connect to MySQL");	
	$db = mysql_select_db("Restaurant", $dbhandle) or die("Could not select the database");
	
	//check if it is online booking or food order in the restaurant
	//if it is food order in the restaurant, then check the sequence number
	$book_online = false;
	$isValid = true;
	$MAX_WINDOW = 4;
	
	//if this is the first time access the page (before submit)
	if(!isset($_GET['submit'])){
		if(isset($_GET['s'])){
			$table = $_GET['t'];
			$seqNum = $_GET['seqNum'];
			
			$sharedKey = getSharedKey($table);

			$max_seq = checkSequence($sharedKey);
			
			//echo "max seq = ".$max_seq."<br>";
			//echo $max_seq."<br>";		
			//if($max_seq >= 0) {
			if ($max_seq < $seqNum && $max_seq >= 0){
				$s = $_GET['s'];
				$table = $_GET['t'];
				//update the database the time the tag is tapped
				$inserted_table = "tbl".$table;
				//$inserted_seq = (int)$max_seq + 1;
				$inserted_seq = (int)$seqNum;
				
				date_default_timezone_set("Europe/Helsinki");
				$inserted_time = date('Y-m-d H:i:s', time());
				
				$query = "insert into ".$inserted_table." values (".$inserted_seq.", '$inserted_time'".", '00/00/0000:00:00:00'".", '$s', 'N'".")";
				mysql_query($query);
				printPage($s, $table);
			}
			else{
				echo "We are sorry! The sequence number is not correct. Please tap your phone on the tag and then submit <br>";			
			}
		}
		else{	
			$book_online = true;	
			printOnlineBookingPage();	
		}
	}
	//if this is the submission
	else{
		$table = $_GET['t'];
		$sharedKey = getSharedKey($table);
			
		if(isset($_GET['s'])){
			$check_result = (string)checkSequenceSubmission();
			echo "check_result = ".$check_result."<br>";
			if(strcmp($check_result, "VALID") == 0) {
				processFoodOrder();
			}
			else if(strcmp($check_result, "NEEDTOCONFIRM") == 0){
				echo "We have received your submission. But please confirm your order with waiters";		
			}
			else if(strcmp($check_result, "INVALID") == 0){
				echo "The submitted URL is not correct. Please tap the phone on the tag and redo the food submission";
			}
		}
		else{
			processOnlineBooking();		
		}
	}
	
	
	function getSharedKey($table){	
		$query = "select sharedKey from sharedKeys where tableNum = $table";
		$result = mysql_query($query);
		//check if result is null or not
		$numOfRows = mysql_num_rows($result);
		if($numOfRows == 0) {
			return "0";		
		}
		
		$row = mysql_fetch_array($result);
		return (string) $row{'sharedKey'};
	}
	
	/*
	Check the sequence number sent along with the URL when a customer taps his phone on the tag
	*/
	function checkSequence($sharedKey){
		
		$s = $_GET['s'];
		$table = $_GET['t'];
		$seqNum = $_GET['seqNum'];
		
		$queried_table = "tbl".$table;		
		$query = "select max(sequence) as max_seq from ".$queried_table ;
	
		$result = mysql_query($query);
		
		//check if result is null or not
		$numOfRows = mysql_num_rows($result);
		if($numOfRows == 0) {
			return 0;		
		}
		//else
		$row = mysql_fetch_array($result);
		$next_seq = $row{'max_seq'} + 1;
		if($next_seq <= $seqNum) {
			//calculate the hash value based on the key, the next sequence
			$hash_seq = hash_hmac('md5', (string)$seqNum.$table, (string)$sharedKey);
	
			//compare the sequence number
			if(strcmp($hash_seq, $s) == 0) {
				return (int)$row{'max_seq'};
			}	
		}
		
		return -1;
	}
		
	//check sequence number of the submission
	function checkSequenceSubmission(){
		global $MAX_WINDOW;
		$s = $_GET['s'];
		$table = $_GET['t'];		
		$queried_table = "tbl".$table;

		//find the sequence number of the submission		
		$query = "select sequence from $queried_table where hmac_sequence like '$s' and submitted = 'N'";
		$result = mysql_query($query);	
		$numOfRows = mysql_num_rows($result);
		
		if($numOfRows == 0) {
			return "INVALID";		
		}
		$row = mysql_fetch_array($result);
		$seq = $row{'sequence'};		
	
		//find the max-sequence submission
		$max_query = "select max(sequence) as msequence, submittedTime from $queried_table where submitted = 'Y'";
		$max_result = mysql_query($max_query);	

		$max_numOfRows = mysql_num_rows($max_result);
		$max_row = mysql_fetch_array($max_result);
		$max_sequence = $max_row{'msequence'};
			
		$max_submittedTime = $max_row{'submittedTime'};		  

		//if the submitted sequence is greater than the max-sequence submission		
		if ($seq > $max_sequence){
			return "VALID";		
		}
		//if the submission is less than 20 minutes from the last submission (in the time windows)
		else{
			//if the seq is in the valid windows
			if($max_sequence - $seq <= $MAX_WINDOW) {
				date_default_timezone_set("Europe/Helsinki");
				$current_time = date('Y-m-d H:i:s', time());
				$diff = strtotime($current_time) - strtotime($max_submittedTime) + 1;
				
				//valid if less than 20 minutes				
				if ($diff > 1200){
					return "NEEDTOCONFIRM";					
				}
				else return "VALID";
			}
			else {
				return "INVALID";			
			}
		}
		return "VALID";
	}
	
	
	function processOnlineBooking() {	
		echo "Enter your address, then pay and commit the payment :P";
	}
	
	function processFoodOrder() {
		echo "Thank you for your submission <br>";
		//update the submitted time
		$s = $_GET['s'];
		$table = $_GET['t'];
				
		$queried_table = "tbl".$table;
		date_default_timezone_set("Europe/Helsinki");
		$current_time = date('Y-m-d H:i:s', time());
		
		$query = "update $queried_table set submittedTime = '$current_time', submitted = 'Y' where hmac_sequence like '$s'";
		
		mysql_query($query);
		$foodchoice = $_GET['ocluoc']." ".$_GET['raumuong']." ".$_GET['ocbungchuoidau']." ".$_GET['bunca'];
		
		//get the maxium sequence number in the submission table
		$seq_query = "select max(num) as max_num from submission";
		$num_result = mysql_query($seq_query);
		$max_row = mysql_fetch_array($num_result);
		$max_num = $max_row{'max_num'};
		$next_num = (int)$max_num + 1;
		
		$insert_query = "insert into submission values(".$next_num.",".$table.", '$foodchoice', '$current_time')";
		mysql_query($insert_query); 
		
		echo "Your submission is done. Thank you <br>";
		
	}
	
	function printPage($s, $t){
		echo "<html><head>";
		echo "<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" />";
		echo "<title>Restaurant example</title>
				<link rel=\"stylesheet\" href=\"mystyle.css\">
				<script type=\"text/javascript\" >
				function handleClick1(){
				var total = document.getElementById('total').value;
				if(document.getElementById('ocluoc').checked){
					total = parseInt(total) + 10;
				}
				else{
					total = parseInt(total) - 10;
				}
				document.getElementById('total').value = total;
			}
			function handleClick2(){
				var total = document.getElementById('total').value;
				if(document.getElementById('ocbungchuoidau').checked){
					total = parseInt(total) + 11;
				}
				else{
					total = parseInt(total) - 11;
				}
				document.getElementById('total').value = total;		
			}
			function handleClick3(){
				var total = document.getElementById('total').value;
				if(document.getElementById('raumuong').checked){
					total = parseInt(total) + 12;
				}
				else{
					total = parseInt(total) - 12;
				}		
				document.getElementById('total').value = total;
			}
			function handleClick4(){
				var total = document.getElementById('total').value;
				if(document.getElementById('bunca').checked){
					total = parseInt(total) + 13;
				}
				else{
					total = parseInt(total) - 13;
				}
				document.getElementById('total').value = total;
			}
		</script>
	</head>";
	
	echo "<body>
			<div id=\"header\">
			<h1>Welcome to Vietnamese Cuisines</h1>	
			</div>
			<div id=\"gutter\"></div>
			<div id=\"col1\">
	
			<table summary=\"\" >
				<tr><td>Menu</td></tr>
				<tr><td>Special offers</td></tr>
				<tr><td> Online reservation</td></tr>
				<tr><td>Opening hours</td></tr>
				<tr><td align=\"middle\"><img style=\"width: 100%\" src=\"costume.jpg\" alt=\"costume\"></td>></tr>
			</table>	
			</div>	
				<form name=\"choice\" method=\"GET\" action=\"mn.php\">
			<div id=\"col2\">
				<img style=\"width: 100%\" src=\"ocluoc.jpeg\" alt=\"oc luoc\"> 
				<br> 
				<p> Price: $10
				<input type=\"checkbox\" name=\"ocluoc\" id=\"ocluoc\" value=\"ocluoc\" onclick=\"handleClick1()\">			
				</p>
				<img style=\"width: 100%\" src=\"ocbungchuoidau.jpg\" alt=\"oc bung chuoi dau\">
				<p> Price: $11
				<input type=\"checkbox\" name=\"ocbungchuoidau\" id=\"ocbungchuoidau\" value=\"ocbungchuoidau\" onclick=\"handleClick2()\">			
				</p>
			</div>
	
			<div id=\"gutter\"></div>
	
			<div id=\"col3\">
				<img style=\"width: 100%\" src=\"raumuong.jpg\" alt=\"rau muong\"> 
				<br>
				<p> Price: $12
				<input type=\"checkbox\" name=\"raumuong\" id=\"raumuong\" value=\"raumuong\" onclick=\"handleClick3()\">
				</p>
		
				<img style=\"width: 100%\" src=\"bunca.jpeg\" alt=\"bun ca\">
				<p> Price: $13
				<input type=\"checkbox\" name=\"bunca\" id=\"bunca\" value=\"bunca\" onclick=\"handleClick4()\">			
				</p>
			</div>
	
			<div id=\"footer\">
				<label>Total: </label>
				<input type = \"hidden\" name = \"s\" value = $s>
				<input type = \"hidden\" name = \"t\" value = $t>
				<input type=\"text\" name=\"total\" id=\"total\" size=\"10\" value=\"0\" readonly=\"true\">
				<input type=\"submit\" name=\"submit\" value=\"Submit\">
			</div>
	
		</form>
	
		</body>
		</html>";
	}
	
	function printOnlineBookingPage(){
		echo "<html><head>";
		echo "<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" />";
		echo "<title>Restaurant example</title>
				<link rel=\"stylesheet\" href=\"mystyle.css\">
				<script type=\"text/javascript\" >
				function handleClick1(){
				var total = document.getElementById('total').value;
				if(document.getElementById('ocluoc').checked){
					total = parseInt(total) + 10;
				}
				else{
					total = parseInt(total) - 10;
				}
				document.getElementById('total').value = total;
			}
			function handleClick2(){
				var total = document.getElementById('total').value;
				if(document.getElementById('ocbungchuoidau').checked){
					total = parseInt(total) + 11;
				}
				else{
					total = parseInt(total) - 11;
				}
				document.getElementById('total').value = total;		
			}
			function handleClick3(){
				var total = document.getElementById('total').value;
				if(document.getElementById('raumuong').checked){
					total = parseInt(total) + 12;
				}
				else{
					total = parseInt(total) - 12;
				}		
				document.getElementById('total').value = total;
			}
			function handleClick4(){
				var total = document.getElementById('total').value;
				if(document.getElementById('bunca').checked){
					total = parseInt(total) + 13;
				}
				else{
					total = parseInt(total) - 13;
				}
				document.getElementById('total').value = total;
			}
		</script>
	</head>";
	
	echo "<body>
			<div id=\"header\">
			<h1>Welcome to Vietnamese Cuisines</h1>	
			</div>
			<div id=\"gutter\"></div>
			<div id=\"col1\">
	
			<table summary=\"\" >
				<tr><td>Menu</td></tr>
				<tr><td>Special offers</td></tr>
				<tr><td> Online reservation</td></tr>
				<tr><td>Opening hours</td></tr>
				<tr><td align=\"middle\"><img style=\"width: 100%\" src=\"costume.jpg\" alt=\"costume\"></td>></tr>
			</table>	
			</div>	
				<form name=\"choice\" method=\"GET\" action=\"mn.php\">
			<div id=\"col2\">
				<img style=\"width: 100%\" src=\"ocluoc.jpeg\" alt=\"oc luoc\"> 
				<br> 
				<p> Price: $10
				<input type=\"checkbox\" name=\"ocluoc\" id=\"ocluoc\" value=\"ocluoc\" onclick=\"handleClick1()\">			
				</p>
				<img style=\"width: 100%\" src=\"ocbungchuoidau.jpg\" alt=\"oc bung chuoi dau\">
				<p> Price: $11
				<input type=\"checkbox\" name=\"ocbungchuoidau\" id=\"ocbungchuoidau\" value=\"ocbungchuoidau\" onclick=\"handleClick2()\">			
				</p>
			</div>
	
			<div id=\"gutter\"></div>
	
			<div id=\"col3\">
				<img style=\"width: 100%\" src=\"raumuong.jpg\" alt=\"rau muong\"> 
				<br>
				<p> Price: $12
				<input type=\"checkbox\" name=\"raumuong\" id=\"raumuong\" value=\"raumuong\" onclick=\"handleClick3()\">
				</p>
		
				<img style=\"width: 100%\" src=\"bunca.jpeg\" alt=\"bun ca\">
				<p> Price: $13
				<input type=\"checkbox\" name=\"bunca\" id=\"bunca\" value=\"bunca\" onclick=\"handleClick4()\">			
				</p>
			</div>
	
			<div id=\"footer\">
				<label>Total: </label>
				<input type=\"text\" name=\"total\" id=\"total\" size=\"10\" value=\"0\" readonly=\"true\">
				<input type=\"submit\" name=\"submit\" value=\"Submit\">
			</div>
	
		</form>
	
		</body>
		</html>";
	}
?>